package com.n.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.n.application.SystemCache;
import com.n.common.BaseAction;
import com.n.dao.EmployeeDao;
import com.n.model.Employee;
import com.n.model.Supplier;

@Controller
@RequestMapping("/employee")
public class EmployeeAction extends BaseAction {
	
	static final String PRE_PATH = "/admin/employee/";
	
	@Autowired
	EmployeeDao employeeDao;
	
	
	@RequestMapping(value="save.do")
	@ResponseBody
	public String save(HttpServletRequest request){
		String sid = request.getParameter("id");
		Employee c = new Employee();
		c.setName(request.getParameter("name"));
		c.setTel(request.getParameter("tel"));;
		c.setStatus(0);
		if(!StringUtils.isEmpty(sid)){
			c.setId(Integer.parseInt(sid));
		}
		employeeDao.merge(c);
		return SUCCESS;
	}
	
	@RequestMapping(value="list.do")
	public String list(HttpServletRequest request, ModelMap model){
		List<Employee> data = (List<Employee>)employeeDao.loadAll(Employee.class);
		model.put("data", data);
		return PRE_PATH + "index";
	}
	
	@RequestMapping(value="load.do")
	@ResponseBody
	public String load(HttpServletRequest request){
		String sid = request.getParameter("id");
		if(StringUtils.isEmpty(sid)){
			return ERROR;
		}
		int id = Integer.parseInt(sid);
		Employee c = employeeDao.load(Employee.class, id);
		JSONObject json = JSONObject.fromObject(c);
		json.put("success", SUCCESS);
		System.out.println(json);
		return json.toString();
	}
	
	@RequestMapping(value="del.do")
	@ResponseBody
	public String del(HttpServletRequest request){
		String sid = request.getParameter("id");
		if(StringUtils.isEmpty(sid)){
			return ERROR;
		}
		int id = Integer.parseInt(sid);
		employeeDao.del(id);
		return SUCCESS;
	}

}
